package x.ovo.wechat.bot;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import x.ovo.wechat.bot.common.entity.event.MessageEvent;
import x.ovo.wechat.bot.common.entity.message.TextMessage;
import x.ovo.wechat.bot.common.event.Event;
import x.ovo.wechat.bot.common.event.EventListener;

import java.io.File;

/**
 * 每日新闻监听器
 *
 * @author ovo, created by 2024/06/12
 */
@Slf4j(topic = "每日新闻")
public class DailyNewsListener extends EventListener<MessageEvent<TextMessage>> {

    private static final String URL = "https://api.qqsuu.cn/api/dm-60s";

    @Override
    public boolean support(Event<?> event) {
        return event instanceof MessageEvent
                && event.getSource() instanceof TextMessage
                && "今日新闻".equals(((MessageEvent<?>) event).getContent());
    }

    @Override
    public void onEvent(MessageEvent<TextMessage> event) {
        try {
            File file = FileUtil.file(this.plugin.getDataFolder(), "daily_news.jpg");
            HttpUtil.downloadFile(URL, file);
            boolean b = this.context.getApi().sendImage(event.getSource().getFromUser().getUserName(), file);
            if (b) {
                log.info("发送每日新闻成功");
            } else {
                log.info("发送每日新闻失败");
            }
        } catch (Exception e) {
            log.error("发送每日新闻失败", e);
        }
    }
}
